package com.huawei.dao;

import com.huawei.bean.User;
import com.huawei.util.DBUtil;
import com.huawei.util.Tools;

import java.sql.*;
import java.util.Arrays;

public class UserDao {
    /**
     * 插入方法(插入user对象数据表)
     * @param user 需要插入的对象
     * @return 返回是否成功
     */
    public static int insertUser(User user){
        int n=0;
        String sql = "insert into user(name,age,gender,birthday,hobbies,createtime) values(?,?,?,?,?,now())";
        Connection connection = DBUtil.getConnection();//获取连接
        try {
            PreparedStatement pst = connection.prepareStatement(sql);
            pst.setString(1,user.getName());
            pst.setInt(2,user.getAge());
            pst.setString(3,user.getGender()+"");
            //利用时间戳创建一个新的生气了的Date类
            pst.setDate(4, new Date(user.getBirthday().getTime()));
            //使用工具类将其转化为字符串
            pst.setString(5, Tools.arraysToString(user.getHobbies()));
            n=pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return n;
    }

    /**
     * 查询方法(通过id查询)
     * @param id 需要查询的id
     * @return 返回的对象
     */
    public static User findUserById(int id){
        User user=null;
        String sql = "select * from user where id=?";
        PreparedStatement pst=null;
        ResultSet rs=null;
        Connection conn = DBUtil.getConnection();
        try {
             pst = conn.prepareStatement(sql);
            pst.setInt(1,id);
            rs = pst.executeQuery();
            while (rs.next()){
                user = new User();
                user.setId(rs.getInt("id"));
                user.setName(rs.getString("name"));
                user.setAge(rs.getInt("age"));
                user.setGender(rs.getString("gender").charAt(0));
                user.setBirthday(rs.getDate("Birthday"));
                user.setHobbies(new String[]{rs.getString("Hobbies")});

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(rs,pst,conn);
        }
        return  user;

    }
}
